import { Component, OnInit, OnDestroy, ElementRef } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { OverlayService, LatLonArray } from 'unified-map';
import { TypeMapper } from '../one-map';
import { MapUiService } from '../map-ui.service';
import { TreeNode } from '../monitor-major';
import { DialogPumpComponent } from "../dialog-pump/dialog-pump.component";
import { DialogSectionComponent } from "../dialog-section/dialog-section.component";
import { DialogGateComponent } from "../dialog-gate/dialog-gate.component";
import { DialogVideoComponent } from '../dialog-video/dialog-video.component';
import { DialogIntakeComponent } from '../dialog-intake/dialog-intake.component';
import { OneMapService } from '../one-map.service';

@Component({
  selector: 'app-monitor-major',
  templateUrl: './monitor-major.component.html',
  styleUrls: ['./monitor-major.component.scss']
})
export class MonitorMajorComponent implements OnInit, OnDestroy {
  private unsubscribe = new Subject<void>();
  init: boolean = true;
  treeNode: any[] = [];
  panelItem: any = {
    mode: "major",
    layerName: "zygq"
  };
  typeMapper: any = TypeMapper;
  // dmArr: string[] = ['hh', 'gqdm', 'shg', 'psg', 'hd', 'yz', 'skswz', 'ylz', 'cyylz', 'sqz'];
  pageNum: number = 1;
  pageSize: number = 100;
  monitorData: any = {};
  interval: any;

  constructor(
    private mapUiService: MapUiService,
    private overlayService: OverlayService,
    private mapService: OneMapService,
    private elementRef: ElementRef
  ) { }

  ngOnInit(): void {
    this.treeNode = TreeNode;
    this.mapUiService.modeChange.next("major");
    this.mapUiService.treeNodeChange.next({
      treeNode: this.treeNode,
      initMap: true
    });
    // setTimeout(() => {
    //   this.mapUiService.treeNodeChange.next({
    //     treeNode: this.treeNode,
    //     initMap: false
    //   });
    // }, 1000);
    this.mapUiService.panelChange.next(this.panelItem);
    this.mapUiService.entityClicked
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(entity => {
        this.entityClicked(entity);
      });
    this.mapUiService.buildingSelected
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(data => {
        // console.log(data);
        this.createOverlay(data);
      });
    this.mapUiService.searchSelected
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(item => {
        this.onSearchSelect(item);
      });
    this.mapUiService.nodeSelectChange.subscribe(node => {
      this.updateMonitorData();
    });
    this.mapUiService.labelOffChange.subscribe(node => {
      this.treeNode.map(n => {
        if (n.layerName == node.layerName) {
          n.labelOff = node.labelOff;
        }
      });
    });
    this.init = false;
    // this.interval = setInterval(() => {
    this.updateMonitorData();
    // }, 30 * 1000);
    this.mapUiService.getMapInstance().then(() => {
      setTimeout(() => {
        this.updateMonitorData();
      }, 2000);
    });
  }

  ngOnDestroy(): void {
    clearInterval(this.interval);
    this.interval = null;
    this.overlayService.clear();
    this.unsubscribe.next();
    this.unsubscribe.complete();
  }

  updateMonitorData() {
    this.treeNode.map(node => {
      if (node.checked && node.layerName) {
        this.getMonitorList(node.layerName);
      }
    });
  }

  getMonitorList(layerName) {
    const statType = layerName.split("_").pop();
    this.mapService
      .queryMonitorList({
        type: statType,
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
      }).subscribe(res => {
        const list = res['list'];
        let oldList = this.monitorData[statType];
        if (oldList) {
          list.map((item, i) => {
            let oldData = oldList[i];
            let change = false;
            switch (statType) {
              case 'cyylz':
                change = item.dyp != oldData.dyp;
                break;
              case 'gyjc':
              case 'nyjc':
              case 'shjc':
              case 'hhjc':
                change = item.mpQ != oldData.mpQ;
                break;
              case 'hh':
                change = item.waterHeight != oldData.waterHeight || item.flux != oldData.flux || item.heightInside != oldData.heightInside || item.fluxIncome != oldData.fluxIncome;
                break;
              case 'zygq':
              case 'zypsg':
                change = item.waterHeight != oldData.waterHeight || item.flux != oldData.flux;
                break;
              case 'zyzm':
                change = item.degreeMax != oldData.degreeMax || item.validStrobe != oldData.validStrobe;
                break;
              case 'zybz':
                change = item.instanFlow != oldData.instanFlow;
                break;
            }
            if (change) {
              oldData = {
                ...item,
                change: true
              };
              this.mapUiService.updatePointEntity(
                layerName,
                `${layerName}-${item.stadiaCode || item.stcd || item.wiuCd || item.strobeCode || item.pumpCode}`,
                {},
                {
                  text: this.getMonitorText(statType, item)
                }
              );
            }
          });
        } else if (list) {
          oldList = [];
          list.map((item, i) => {
            oldList[i] = {
              ...item,
              change: false
            };
            this.mapUiService.updatePointEntity(
              layerName,
              `${layerName}-${item.stadiaCode || item.stcd || item.wiuCd || item.strobeCode || item.pumpCode}`,
              {},
              {
                text: this.getMonitorText(statType, item)
              }
            );
          });
          this.monitorData[statType] = oldList;
        }
      });
  }

  getMonitorText(type, item) {
    let text;
    switch (type) {
      case 'cyylz':
        text = `${item.stadiaName} ${item.dyp || '-'}mm`;
        break;
      case 'gyjc':
      case 'nyjc':
      case 'shjc':
      case 'hhjc':
        text = `${item.wiuNm} ${item.mpQ}m³/s`;
        break;
      case 'hh':
        text = `${item.stadiaName} ${item.waterHeight || item.heightInside}m ${item.flux || item.fluxIncome || '-'}m³/s`;
        break;
      case 'zygq':
      case 'zypsg':
        if (item.pumpName) {
          text = `${item.pumpName} ${item.instanFlow}m³/s`;
        } else {
          text = `${item.stadiaName} ${item.waterHeight}m ${item.flux}m³/s`;
        }
        break;
      case 'zyzm':
        text = `${item.watergateCode} ${item.degreeMax}m (${item.validStrobe})`;
        break;
      case 'zybz':
        text = `${item.pumpName} ${item.instanFlow}m³/s`;
        break;
    }
    return text;
  }

  entityClicked(entity) {
    console.log("----------entityClicked monitor-----------");
    if (!entity || !entity.layer || entity.layer == "boundary" || this.init) {
      if (this.mapUiService.twinkleOverlay) {
        this.mapUiService.twinkleOverlay.setPosition(null);
      }
      this.mapUiService.showTwinkle = false;
      return;
    }

    const latLon = this.mapUiService.mapInstance.getPositionByEntity(
      entity.layer,
      entity.id
    );
    const layer = entity.layer.split("_").pop();
    this.createOverlay({ ...entity, latLon, layer });
  }

  entityHovered(entity) { }

  createOverlay(item): void {
    let overlayName;
    let title;
    let location;
    if (!item.overlayName) {
      title = item.properties && item.properties.name;
      switch (item.layer) {
        case "bengzhan":
          overlayName = DialogPumpComponent;
          title = title || item.pumpName;
          break;
        case "jinshuizha":
        case "jiezhizha":
        case "tuishuizha":
        case "zhikaikou":
        case "zyzm":
          overlayName = DialogGateComponent;
          title = title || item.watergateCode;
          break;
        case 'video':
          overlayName = DialogVideoComponent;
          break;
        case 'db': // 地表取水口
        case 'dx': // 地下取水口
        case 'gy': // 工业取水口
        case 'ny': // 农业取水口
        case 'sh': // 生活取水口
        case 'gyjc': // 工业取水口
        case 'nyjc': // 农业取水口
        case 'shjc': // 生活取水口
        case 'hhjc': // 生活取水口
          overlayName = DialogIntakeComponent;
          title = title || item.properties && item.properties.wiust_nm || item.wiuNm;
          break;
        case 'hd': // 河道水文站
        case 'yz': // 堰闸水文站
        case 'hh': // 黄河断面
        case 'skswz': // 水库水文站
        case 'gqdm': // 干渠断面
        case 'zygq': // 干渠断面
        case 'shg': // 山洪沟断面
        case 'psg': // 排水沟断面
        case 'zypsg': // 排水沟断面
        case 'ylz': // 雨量站
        case 'cyylz': // 常用雨量站
        case 'sqz': // 墒情站
          overlayName = DialogSectionComponent;
          title = title || item.stadiaName || item.properties && item.properties.Stadia_Name;
          break;
      }
      location = item.latLon
        ? item.latLon
        : item.geom
          ? [item.geom.lng, item.geom.lat]
          : [];
    } else {
      overlayName = item.overlayName;
      title = item.name;
      location = item.location;
    }

    if (!overlayName || !location.length) {
      return;
    }

    this.overlayService.clear();
    const h = this.mapUiService.mainCompEl.nativeElement.getBoundingClientRect()
      .height;
    const overlayHeight = item.layer == 'video' ? 650 : 450;
    const overlayPTop = Math.abs(h - overlayHeight - 50) / 2 + overlayHeight;
    this.mapUiService.mapInstance
      .flyTo(location as LatLonArray, {
        zoom: this.mapUiService.currentZoom > 12 ? this.mapUiService.currentZoom : 12,
        duration: 500,
        padding: [overlayPTop, 0, 0, 0]
      })
      .then(() => {
        this.overlayService.createOverlay(
          overlayName,
          {
            longitude: location[0],
            latitude: location[1],
            title,
            showLeader: true,
            width: item.layer == 'video' ? 1020 : 600,
            height: overlayHeight,
            offset: { x: 0, y: -15 },
            singleton: true,
            destroyOnClose: true,
            opacity: 0.8,
            data: item
          },
          true
        );
      });
  }

  onSearchSelect(item) {
    // console.log(item);
    let overlayName;
    switch (item.type) {
      case 1:
        overlayName = DialogPumpComponent;
        break;
      case 9:
      case 12:
        overlayName = DialogGateComponent;
        break;
      case 27:
      case 28:
        overlayName = DialogIntakeComponent;
        break;
      case 18:
      case 19:
      case 20:
      case 21:
      case 22:
      case 23:
      case 24:
      case 25:
      case 26:
        overlayName = DialogSectionComponent;
        break;
    }
    if (overlayName) {
      const location = item.longitude ? [item.longitude, item.latitude] : [item.geom.lng, item.geom.lat];
      this.createOverlay({
        ...item,
        name: item.buildName,
        code: item.buildCode,
        location,
        overlayName,
        layer: this.typeMapper[item.type]
      });
    }
  }
}
